<?php
/**
 * @author Feng
 * @date 2012-6-1
 */
class controller_admin_picture_photo extends system_user_control {
	
	private $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		$this->concept = new picture_photo_localeConcept($this->user->getLang());
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Pictures'))->setRoute('picture/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Photos'))->setRoute('picture/photo/index'));
	}
		
	public function action_index() {
		$this->_goRoute('picture/photo/list');
		$this->render();
	}
	
	public function action_batch() {
		$concept = new picture_special_concept($this->user->getLang());
		$special_id = intval($this->_param('special_id'));	
		$this->view->step = $step = intval($this->_post('next'));
		if($this->getRequest()->isPost() && $step == 1) {
			$this->referer = $this->_post('referer');
			try {
				$sids = (array) $this->_post('special_id');
				$sids[$special_id] = $special_id;
				$sid = implode(', ', $sids);		
				
				$_photo = (array) $this->_post('photo_id');
				$_photo[] = 0;
				$id = implode(', ', $_photo);

				$this->view->specialList = $concept->fetchAll(array("special.id IN($sid)"));		
				$list = $this->concept->fetchAll(array("photo.id IN($id)"));
				
				$pids = $locale = $keyword = array();
				foreach($list AS $_row) {
					$pids[$_row->getId()] = $_row->getId();
				}
				if(!empty($pids)) {
					$pid = implode(', ', $pids);
					$concept = new picture_photo_locale_concept();
					foreach($concept->fetchAll(array("photo_id IN($pid)", 'lang = ?' => $this->user->getLang())) AS $_row) {
						$locale[$_row->getPhotoId()] = $_row;
					}	
					$_kw = array();		
					$concept = new resource_keyword_concept();
					foreach($concept->fetchAll(array("id IN (SELECT `keyword_id` FROM `picture_photo_keyword` WHERE `photo_id` IN($pid))")) AS $_row) {
						$_kw[$_row->getId()] = $_row->getName();
					}
					if(!empty($_kw)) {
						$pid = implode(', ', array_keys($_kw));
						$concept = new picture_photo_keyword_concept();
						foreach($concept->fetchAll(array("keyword_id IN($pid)")) AS $_row) {
							if(!isset($_kw[$_row->getKeywordId()])) continue;
							$keyword[$_row->getPhotoId()][] = $_kw[$_row->getKeywordId()];
						}
					}
				}

				$this->view->locale = $locale;
				$this->view->keyword = $keyword;
				$this->view->list = $list;				
			} catch (Exception $e) {
				$this->view->step = 0;
				$this->view->throwException = $e;
			}
		} elseif($this->getRequest()->isPost() && $step == 2) {
			$this->referer = $this->_post('referer');
			try {				
				foreach((array) $this->_post('photo') AS $id => $_photo) {
					if(!($row = $this->concept->fetch(array('id = ?' => $id)))) {
						continue;
					}
					try {
						system_db::getAdapter()->beginTransaction();
						$row->getLocale()->setTitle(trim($_photo['title']));
						$row->getLocale()->setDescription($_photo['description']);
						$row->setDisplayOrder(intval($_photo['display_order']));
						$row->setKeywords($_photo['tag']);
						$row->save(false);
						system_db::getAdapter()->commit();
					} catch (Exception $ex) {
						system_db::getAdapter()->rollBack();
					}
				}
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				$this->view->step = 0;
				$this->view->throwException = $e;
			}
		} else {
			$specialList = array();
			$isInList = false;
			foreach($concept->fetchAll(array(), array('special.creationtime DESC'), 10) AS $row) {
				if($special_id == $row->getId()) $isInList = true;
				$specialList[] = $row;
			}
			if(!$isInList && $row = $concept->fetch(array('special.id = ?' => $special_id))) {
				array_unshift($specialList, $row);
			}
			$this->view->specialList = $specialList;
		}
		$this->view->special_id = $special_id;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('UPLOAD IN BATCHES'))->setRoute('picture/photo/batch')->setParams(array('special_id' => $special_id)));
		$this->render();
	}
	
	public function action_addnew() {
		$row = $this->concept->create();
		$row->setIsActive(1);
		$row->setDisplayOrder(0);
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('New Photo'))->setRoute('picture/photo/addnew'));
		$this->render('picture/photo/row.phtml');
	}
	
	public function action_edit() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('photo.id = ?' => $id)))) {
			throw new picture_exception("The Photo is not Existing.");
		}		
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/photo/edit')->setParams(array('id' => $row->getId())));
		$this->render('picture/photo/row.phtml');
	}
	
	private function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$this->referer = $this->_post('referer');
		$row->getLocale()->setTitle(trim($this->_post('title')));
		$row->getLocale()->setDescription($this->_post('description'));
		$row->setDisplayOrder(intval($this->_post('display_order')));
		$row->setIsActive(intval($this->_post('is_active')) ? 1 : 0);
		$row->setIsRecommend(intval($this->_post('is_recommend')) ? 1 : 0);
		$row->setKeywords(trim($this->_post('tag')));
		if(!isset($_FILES['hash']) || (!is_uploaded_file($_FILES['hash']['tmp_name']) && !$row->getId())) {
			$this->view->throwException = "Please select a Photo you want to upload";
			return $row;
		}
		$this->_saveToDatabase($row, 'hash', 'image');
		return $row;
	}
	
	public function action_list() {
		$checkedList = array();
		if($this->getRequest()->isPost() && $this->_post('delete')) {
			//$this->referer = $this->_post('referer');
			$checkedList = (array) $this->_post('photo_id');
			try {
				system_db::getAdapter()->beginTransaction();
				if(empty($checkedList)) {
					throw new picture_exception("No item Selected.");
				}
				$this->_auth();
				$_pid = implode(', ', $checkedList);				
				foreach($this->concept->fetchAll(array("photo.id IN($_pid)")) AS $photo) {
					// 這里有區分本地化資訊,所以隻刪除本地化資訊
					$photo->delete(array('locale_only' => 1, 'reserve_collection' => 1));
				}
				system_db::getAdapter()->commit();
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->view->throwException = $e;
			}
		}
		$this->view->checkedList = $checkedList;
		
		$adapter = new system_paginator_adapter_concept(new picture_photo_concept($this->user->getLang()));
		$adapter->setCurrentPageNumber(intval($this->getRequest()->getParam('page', 1)));
		$keyword = trim($this->_get('keyword'));
		if($keyword == self::$_keyword) $keyword = '';
		if($keyword) {
			$adapter->where("locale.`title` LIKE '%$keyword%'");
		}
		$this->view->order = $order = strtolower($this->getRequest()->getQuery('order'));
		$_order = array("creationtime DESC", "display_order ASC");
		if($order) {
			$this->view->sort = $sort = intval($this->getRequest()->getQuery('sort'));
			switch($order) {
				case 'date': {
					$order = 'lastmodified';
					break;
				}
				default: {
					$sort = !$sort;
					$order = 'display_order';
					break;
				}
			}
			$_sort = !$sort ? 'DESC' : 'ASC';
			$_order = array("$order $_sort");
		}
		$adapter->order($_order);
		$adapter->setLimit(48);
		$this->view->list = new system_paginator($adapter);
		$this->_crumbs()->addPage(system_nav_page::create($this->language('List'))->setRoute('picture/photo/list'));
		$this->render();
	}
}
